// 引入defineStore用于创建store
import { defineStore } from 'pinia'
import MutationTypes from './mutation-types'
type User = Record<string, string | boolean>;
export const useUserStore = defineStore('user', {

    state: (): { loginStatus: boolean, token: string | null, userInfo: User } => ({
        // 登录状态
        loginStatus: false,
        // token
        token: sessionStorage.getItem('token') ?? '',
        // 用户信息：用户的头部|用户
        userInfo: JSON.parse(sessionStorage.getItem('USER_INFO') ?? '{}')
    }),
    getters: {
        [MutationTypes.GET_USER_INFO]: (state): User => state.userInfo
    },
    actions: {
        [MutationTypes.SET_TOKEN](token: string) {
            this.token = token
            sessionStorage.setItem('token', token)
        },
        // 登录
        [MutationTypes.USER_LOGIN](user: User) {
            this.loginStatus = true
            this.userInfo = user
            sessionStorage.setItem('USER_INFO', JSON.stringify(user))
        },
        [MutationTypes.LOGOUT]() {
            this.$reset()
            sessionStorage.clear()
        }
    }
})